import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

// 路由懒加载
const Login = () => import("@/views/login/index.vue");
const Layout = () => import("@/views/layout/index.vue");
const ProductList = () => import("@/views/product/list.vue");
const ProductAdd = () => import("@/views/product/add.vue");
const OrderList = () => import("@/views/order/list.vue");
const OrderAdd = () => import("@/views/order/add.vue");
const UserList = () => import("@/views/user/list.vue");
const UserAdd = () => import("@/views/user/add.vue");
const Demo = () => import("@/views/demo/index.vue");

const routes = [
	{
		path: "/login",
		name: "Login",
		component: Login,
		meta: { title: "登录" },
	},
	{
		path: "/",
		component: Layout,
		redirect: "/product/list",
		meta: { requiresAuth: true },
		children: [
			// 商品管理
			{
				path: "/product/list",
				name: "ProductList",
				component: ProductList,
				meta: { title: "商品管理", icon: "el-icon-goods" },
			},
			{
				path: "/product/add",
				name: "ProductAdd",
				component: ProductAdd,
				meta: { title: "新增商品", icon: "el-icon-plus" },
			},
			// 订单管理
			{
				path: "/order/list",
				name: "OrderList",
				component: OrderList,
				meta: { title: "订单管理", icon: "el-icon-s-order" },
			},
			{
				path: "/order/add",
				name: "OrderAdd",
				component: OrderAdd,
				meta: { title: "新增订单", icon: "el-icon-plus" },
			},
			// 用户管理
			{
				path: "/user/list",
				name: "UserList",
				component: UserList,
				meta: { title: "用户管理", icon: "el-icon-user" },
			},
			{
				path: "/user/add",
				name: "UserAdd",
				component: UserAdd,
				meta: { title: "新增用户", icon: "el-icon-plus" },
			},
			{
				path: "/demo/index",
				name: "demo",
				component: Demo,
				meta: { title: "demo", icon: "el-icon-plus" },
			},
		],
	},
	// 404路由
	{
		path: "*",
		redirect: "/404",
	},
];

const router = new VueRouter({
	mode: "history",
	//   base: process.env.BASE_URL,
	routes,
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
	// 设置标题
	document.title = to.meta.title || "积分管理系统";

	// 检查是否需要登录权限
	if (to.meta.requiresAuth) {
		const token = localStorage.getItem("token");
		if (!token) {
			// 没有token，跳转到登录页
			next({
				path: "/login",
				query: { redirect: to.fullPath },
			});
			return;
		}
	}

	next();
});

export default router;
